import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';
import { RootState } from '../store';
import { getAddressList, IAddress } from 'services/address';

const namespace = 'address/list';

interface IInitialState {
  loading: boolean;
  page_num: number;
  page_size: number;
  total: number;
  addressList: IAddress[];
}

const initialState: IInitialState = {
  loading: true,
  page_num: 1,
  page_size: 10,
  total: 0,
  addressList: [],
};

export const getList = createAsyncThunk(
  `${namespace}/getAddressList`,
  async (params: { page_size: number; page_num: number }) => {
    const result = await getAddressList(params);
    return {
      list: result?.data,
      total: result?.total,
      page_size: params.page_size,
      page_num: params.page_num,
    };
  },
);

const addressListSlice = createSlice({
  name: namespace,
  initialState,
  reducers: {
    clearPageState: () => initialState,
  },
  extraReducers: (builder) => {
    builder
      .addCase(getList.pending, (state) => {
        state.loading = true;
      })
      .addCase(getList.fulfilled, (state, action) => {
        console.log('action.....: ', action);
        state.loading = false;
        state.addressList = action.payload?.list;
        state.total = action.payload?.total;
        state.page_size = action.payload?.page_size;
        state.page_num = action.payload?.page_num;
      })
      .addCase(getList.rejected, (state) => {
        state.loading = false;
      });
  },
});

export const { clearPageState } = addressListSlice.actions;

export const selectAddressList = (state: RootState) => {
  console.log("state:", state);
  return state.addressList;
}

export default addressListSlice.reducer;
